package fun.ticsmyc.multiThread;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Ticsmyc
 * @package fun.ticsmyc.multiThread
 * @date 2020-08-16 16:09
 */

class ShareSource{
    public volatile boolean FLAG = true;
    private AtomicInteger number = new AtomicInteger(1);
    private BlockingQueue<String> blockQueue ;
    public  ShareSource(BlockingQueue<String> blockQueue){
        this.blockQueue = blockQueue;
    }

    public void produce() throws InterruptedException {
        while(FLAG){
            String production = number.getAndIncrement()+"";
            boolean offer = blockQueue.offer(production, 2, TimeUnit.SECONDS);
            if(offer){
                System.out.println(Thread.currentThread().getName()+"\t生产"+production+" 成功");
            }else{
                System.out.println(Thread.currentThread().getName()+"\t生产"+production+" 失败");
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"\t生产结束");
    }

    public void consumer() throws InterruptedException {
        while(FLAG){
            String production = blockQueue.poll(2,TimeUnit.SECONDS);
            if(production==null || "".equalsIgnoreCase(production)){
                System.out.println(Thread.currentThread().getName()+"\t没有产品了,2s退出");
                return;
            }
            System.out.println(Thread.currentThread().getName()+"\t消费"+production);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName()+"\t消费结束");
    }

}


public class 生产消费阻塞队列 {

    public static void main(String[] args) {
        ShareSource shareSource = new ShareSource(new ArrayBlockingQueue<String>(7));

        new Thread(()->{
            try {
                shareSource.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"producer").start();

        new Thread(()->{
            try {
                shareSource.consumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"consumer").start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        shareSource.FLAG=false;

    }
}
